package com.houxm.jbapu;

import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Properties;

import javax.naming.NameAlreadyBoundException;
import javax.naming.NameNotFoundException;

import com.houxm.jbapu.pool.ConnectionPool;
import com.houxm.jbapu.pool.ConnectionPoolManager;

public class Config {
	private static boolean initFlag = false;
	
	private static ConnectionPool cp = null;
	
	/**
	 * 对MySql数据库进行初始化，将会将MySql中所有的数据库、表结构load进内存.
	 * @throws ClassNotFoundException
	 * @throws SQLException
	 */
	public static void init() {
		if(!initFlag) {
			try {
				String url = null;
				String driver = null;
				String username = null;
				String password = null;
				Properties prop = new Properties();
				InputStream is = Config.class.getResourceAsStream("/db.properties");
				prop.load(is);
				driver = prop.getProperty( "driver" ).trim();
				url = prop.getProperty( "url" ).trim();
				username = prop.getProperty( "username" ).trim();
				password = prop.getProperty( "password" ).trim();
				is.close();
				
				cp = ConnectionPoolManager.buildDefaultPool(driver, url, username, password);
				TableUtils tu = new TableUtils();
				tu.bundle();
				initFlag = true;
			} catch (ClassNotFoundException e) {
				e.printStackTrace();
			} catch (SQLException e) {
				e.printStackTrace();
			} catch (NameAlreadyBoundException e) {
				e.printStackTrace();
			} catch (IllegalAccessException e) {
				e.printStackTrace();
			} catch (InstantiationException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
	
	public Connection getConn() throws ClassNotFoundException, SQLException {
		Connection conn = cp.getConnection();
		if(conn==null) {
			try {
				cp = ConnectionPoolManager.getDefaultPool();
			} catch (NameNotFoundException e) {
				e.printStackTrace();
			}
			if(cp==null) {
				init();
			}
			conn = cp.getConnection();
		}
		return conn;
	}
	
	public static void main(String[] args) {
		/*Connection conn = null;
		String url = null;
		String driver = null;
		String username = null;
		String password = null;
		Config c = new Config();
		try {
			Properties prop = new Properties();
			InputStream is = c.getClass().getResourceAsStream("/db.properties");
			prop.load(is);
			driver = prop.getProperty( "driver" ).trim();
			url = prop.getProperty( "url" ).trim();
			username = prop.getProperty( "username" ).trim();
			password = prop.getProperty( "password" ).trim();
			is.close();
			System.out.println(driver);
		} catch (IOException e) {
			e.printStackTrace();
		}*/
	}

}
